package com.example.recruitment.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求的URI
        String uri = request.getRequestURI();
        
        // 如果是登录或注册相关的请求，直接放行
        if (uri.contains("/login") || uri.contains("/register") || 
            uri.contains("/error") || uri.contains("/static/")) {
            return true;
        }
        
        // 获取session
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        
        // 如果用户未登录
        if (user == null) {
            // 保存原始请求URL
            String originalUrl = request.getRequestURI();
            if (request.getQueryString() != null) {
                originalUrl += "?" + request.getQueryString();
            }
            session.setAttribute("originalUrl", originalUrl);
            
            // 重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        
        return true;
    }
} 